const localHost = window.location.host;
const local = window.localStorage;
import $ from 'jquery'
import {Indicator, MessageBox, Toast} from 'mint-ui'
import ciphertext from '../ciphertext/ciphertext.js'

export default {
  localHost: window.location.host,
  isLocalHost: localHost.indexOf('localhost') !== -1 || localHost.indexOf('192') !== -1,

  init() {
    Number.prototype.toFixed = function (d) {
      var s = this + "";
      if (!d) d = 0;
      if (s.indexOf(".") == -1) s += ".";
      s += new Array(d + 1).join("0");
      if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
        var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
        if (a == d + 2) {
          a = s.match(/\d/g);
          if (parseInt(a[a.length - 1]) > 4) {
            for (var i = a.length - 2; i >= 0; i--) {
              a[i] = parseInt(a[i]) + 1;
              if (a[i] == 10) {
                a[i] = 0;
                b = i != 1;
              } else break;
            }
          }
          s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");

        }
        if (b) s = s.substr(1);
        return (pm + s).replace(/\.$/, "");
      }
      return this + "";
    };
  },

  formatTime(seconds, secondsTop, stopBet) {
    let _seconds = !stopBet ? seconds : secondsTop;
    let hour = Math.floor((_seconds / 3600));
    hour = hour < 10 ? '0' + hour : hour;
    hour = hour <= 0 ? '00' : hour;
    let minite = Math.floor((_seconds / 60) % 60);
    minite = minite < 10 ? '0' + minite : minite;
    let second = Math.floor(_seconds % 60);
    second = second < 10 ? '0' + second : second;
    // console.log('minite',minite.charAt(0) +','+ minite.charAt(1))
    // let str = ''
    return (hour + ':' + minite + ':' + second);
  },
  post(self, url, param, successCallback, errorCallback, type, loadingTrue,isProfit) {
    let that = this;
    loadingTrue = !loadingTrue ? true : false;
    if (loadingTrue) {
      that.loadingOpen();
    }
    let startTime = new Date();
    if (that.isLocalHost) {
      // param.bind_account = 1;
    }
    // param.iaddr = that.getItem("isipsa");
    param.token = that.getCookie('token');
    $.ajax({
      url: url,
      type: type || 'get',
      data: param,
      dataType: 'json',
      beforeSend: function (request) {
        request.setRequestHeader("client", "pc");
      },
      // timeout: 1000 * 30,
      success: function (data) {
        // that.closeLoading(self);
        // console.group(url);
        // console.debug("%c参数", "font-weight:bold;color:black;");
        // console.debug(JSON.stringify(param));
        // console.debug("%c返回", "font-weight:bold;color:black;");
        // console.debug(JSON.stringify(data).substring(0, 100));
        // console.debug("%c耗时", "font-weight:bold;color:black;");
        // console.debug((new Date().getTime() - startTime) + ' 毫秒');
        // console.groupEnd();
        //
        // console.log(JSON.parse(JSON.stringify(data)));
        // console.log(JSON.parse(JSON.stringify(data.data)));
        // data.code = 10002
        that.loadingClose();
        if (parseInt(data.code) === 0) {
          successCallback && successCallback(data.data, data);
          sessionStorage.setItem('beforeLoginRouteName', '' + self.$route.name);
        } else {
          let loginRouter = self.$router.history.current.name;
          // console.log('loginRouter', loginRouter);
          switch (parseInt(data.code)) {
            case 97:
              self.$router.push({name: 'topUp',query:{id:4}});
              that.showAlert(data.msg);
              break;
            case 98:
            case 95:
              self.$store.commit('POST_LOGIN_STATUS', false);
              that.setItem('loginStatus', false);
              if (loginRouter === 'index'||loginRouter === 'luckDraw') {
                false;
              } else {
                self.$router.push({name: 'login'});
                if(!isProfit) that.showAlert(data.msg);
              }
              break;
            case 99:
              if (loginRouter === 'userInfo') {
                self.$router.push({name: 'userInfo'});
                that.showAlert(data.msg);
              }
              break;
            case -1:
              that.showAlert(data.msg);
              break;
            default:
              that.showAlert(data.msg);
              break;
          }
          errorCallback && errorCallback(data);
        }
      },
      error: function (XMLHttpRequest) {
        that.loadingClose();
        that.ajaxError(XMLHttpRequest, that);
      }
    });
  },
  DEMANDGET (self, url, param, demand, successCallback, errorCallback, loadingTrue) {
    let that = this;
    loadingTrue = !loadingTrue ? true : false;
    if (loadingTrue) {
      that.loadingOpen();
    }
    // param.client = "h5";
    //请求方式
    demand = !demand ? 'get' : 'post';
    // if (demand === 'post') {
    //   param.token = that.getCookie('token') || '';
    // }
    let assembly = ""; // 拼接
    param.forEach((v)=> {
      assembly += '/' + v;
    });
    $.ajax({
      url: url + assembly,
      type: demand,
      // data: param,
      dataType: "json",
      beforeSend: function(request) {
        request.setRequestHeader("client", "pc");
      },
      success: function (data) {
        that.loadingClose();
        let code = parseInt(data.code);
        // self.$store.commit('LOGIN_STATUS',  that.getItem('loginS'));
        if (code === 0) {
          successCallback && successCallback(data.data, data);
        } else {
          let loginRouter = self.$router.history.current.name;

          switch (parseInt(data.code)) {
            case 97:
              self.$router.push({name: 'topUp',query:{id:4}});
              that.showAlert(data.msg);
              break;
            case 98:
            case 95:
              self.$store.commit('POST_LOGIN_STATUS', false);
              that.setItem('loginStatus', false);
              if (loginRouter === 'index'||loginRouter === 'luckDraw') {
                false;
              } else {
                self.$router.push({name: 'login'});
                if(!isProfit) that.showAlert(data.msg);
              }
              break;
            case 99:
              if (loginRouter === 'userInfo') {
                self.$router.push({name: 'userInfo'});
                that.showAlert(data.msg);
              }
              break;
            case -1:
              that.showAlert(data.msg);
              break;
            default:
              that.showAlert(data.msg);
              break;
          }
          errorCallback && errorCallback(data);
        }
      },
      error: function (XMLHttpRequest) {
        that.loadingClose();
        that.ajaxError(XMLHttpRequest, self);
      }
    })
  },
  ajaxError(response, self) {
    switch (response.status) {
      case 0: // 网络不通
        self.showAlert('网络暂时未能连通');
        break;
      case 401: // 未登录
      case 521: // 超时
        self.showAlert('网络超时');
        break;
      case 522: // 错误
        break;
      case 523:
        self.showAlert('当前时间存在较大偏差');
        break;
      case 524:
        self.showAlert('未找到相关数据');
        break;
      default:
        self.showAlert('服务器异常');
        break
    }
  },

  openLoading(self, options, callback) {
    self.$loading.open();
  },

  closeLoading(self, options, callback) {
    self.$loading.close();
  },
  //终端判别
  browser() {
    //判断访问终端
    let browser = {
      versions: function () {
        let u = navigator.userAgent, app = navigator.appVersion;
        return {
          trident: u.indexOf('Trident') > -1, //IE内核
          presto: u.indexOf('Presto') > -1, //opera内核
          webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
          gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
          mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
          ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
          android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
          iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
          iPad: u.indexOf('iPad') > -1, //是否iPad
          webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
          weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
          qq: u.match(/\sQQ/i) == "qq" //是否QQ
        };
      }(),
      language: (navigator.browserLanguage || navigator.language).toLowerCase()
    }
    return browser;
  },
  //数组去重
  deWeight(arr) {
    let result = [], i, j;
    let repeatNum = [];
    let len = arr.length;
    for (i = 0; i < len; i++) {
      for (j = i + 1; j < len; j++) {
        if (arr[i] === arr[j]) {
          repeatNum.push(arr[i]);
          j = ++i;
        }
      }
      result.push(arr[i]);
    }
    return {result, repeatNum};
  },
  //消息弹框
  showAlert(message, vtrue, position) {
    if (vtrue) return;
    $('.Popup').fadeIn('fast');
    $('.Popup_text p').text(message);
    $('.Popup_text').addClass("zoomIn");
    $('.Popup_text').removeClass("zoomOut");
    setTimeout(function () {
      $('.Popup_text').removeClass("zoomIn");
      $('.Popup_text').addClass("zoomOut");
      $('.Popup').fadeOut();
    }, 1500);
    /* if ($('body').find(".Popup-toast").length > 0) {
       return false;
     } else {
       /!*Toast({
         message: message,
         position: position || 'middle',
         duration: 1500
       });*!/

     }*/

  },
  //消息盒子
  showMessage(self, messageObj, confirmFun, cancelFun, status, btnText) {
    $('.messageMask').fadeIn('fast');
    // messageObj = {title:'', content:[],}  //messageObj数据格式
    self.$store.commit('MESSAGE_BOX_INFO', messageObj);
    status = !status ? -1 : status;
    if (status === 1) {
      $(".cancleMessage").fadeOut(10);
    }
    if (btnText) {
      $(".confirmMessage").html(btnText);
    }
    $(".cancleMessage").on("click", () => {
      $('.messageMask').fadeOut('fast');
      cancelFun && cancelFun();
    });
    $(".confirmMessage").on("click", () => {
      confirmFun && confirmFun();
      $('.messageMask').fadeOut('fast');
    });
  },
  bank(self, address) {
    if (!address) {
      self.$router.back(-1);
    } else {
      self.$router.replace({name: address});
    }
  },
  shortMessage(second) {
    let secondText = '';
    if (second <= 0) {
      secondText = '获取验证码';
    } else {
      secondText = second + 's后重新获取';
    }
    return secondText
  },
  //加密
  hexMd5(val) {
    return ciphertext.hex_md5(val);
  },
  isPhoneNumber(phoneNumber) {
    let myreg01 = /^(13|14|15|18|17)[0-9]{9}$/;
    return myreg01.test(phoneNumber);
  },
  isNumber(value) {
    let pattern = new RegExp("[`~!@#$^&*()=|{}\\+\\- ':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？%]");
    return result = value.match(pattern);
  },
  drop(obj, parentNode) {
    let block = document.getElementById(obj);
    let oW, oH;
    let oLeft, oTop;
    // 绑定touchstart事件
    block.addEventListener("touchstart", function (e) {
      let touches = e.touches[0];
      oW = touches.clientX - block.offsetLeft;
      oH = touches.clientY - block.offsetTop;
      //阻止页面的滑动默认事件
      document.addEventListener("touchmove", defaultEvent, false);
    }, false);

    block.addEventListener("touchmove", function (e) {
      let touches = e.touches[0];
      oLeft = touches.clientX - oW;
      oTop = touches.clientY - oH;
      if (oLeft < 0) {
        oLeft = 0;
      } else if (oLeft > document.documentElement.clientWidth - block.offsetWidth) {
        oLeft = (document.documentElement.clientWidth - block.offsetWidth);
      }
      // else if(oLeft>block.offsetWidth&&oLeft<(document.documentElement.clientWidth/2-block.offsetWidth)){
      //    oLeft=0;
      // }
      let footerHeight = $(".footerNavBar").height();
      if (oTop < 0) {
        oTop = 0;
      } else if (oTop > document.documentElement.clientHeight - block.offsetHeight - footerHeight) {
        oTop = (document.documentElement.clientHeight - block.offsetHeight - footerHeight);
      }
      block.style.left = oLeft + "px";
      block.style.top = oTop + "px";
    }, false);

    block.addEventListener("touchend", function () {
      document.removeEventListener("touchmove", defaultEvent, false);
      if (oLeft > 0 && oLeft < (document.documentElement.clientWidth / 2 - block.offsetWidth)) {
        oLeft = 0;
        block.style.left = oLeft + "px";
        block.style.transition = "left 200ms ease-out";
      }
      if (oLeft > (document.documentElement.clientWidth / 2 - block.offsetWidth) && oLeft < (document.documentElement.clientWidth - block.offsetWidth)) {
        oLeft = document.documentElement.clientWidth - block.offsetWidth;
        block.style.left = oLeft + "px";
        block.style.transition = "left 200ms ease-out";
      }

    }, false);

    function defaultEvent(e) {
      e.preventDefault();
    }
  },
  setItem(key, val) {
    local.setItem(key, JSON.stringify(val));
  },
  judgeXG(id) {
    // id = parseInt(id);
    // id = (id === 0) ? 7 : id;
    id = parseInt(id) === 0 ? '002' : id;
    if (id === '008' || id === '002' || id === '004' || id === '006' || id === '016' || id === '018' || id === '026') {
      return false;
    } else {
      return true;
    }
  },
  getItem(key) {
    try {
      return JSON.parse(local.getItem(key))
    } catch (err) {
      return null
    }
  },
  characterString(string) {
    //字符串转换数组
    return string.split(',');
  },
  getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
  },
  formateNumber(num) {
    let newNum = '';
    let start;
    let end;
    // console.log("num.split()", num.split());
    num.split('').forEach((v, i) => {
      start = -3 * (i + 1);
      if (i == 0) {
        newNum = num.slice(start);
        end = start;
      } else {
        if (num.slice(start, end)) {
          newNum = num.slice(start, end) + ',' + newNum;
          end = start;
        } else {
          return false;
        }
      }
    });
    return newNum;
  },
  loadingOpen() {
    Indicator.open({
      spinnerType: 'fading-circle'
    });
  },
  totalAmount(order, status, officialLetter) {
    let len = order.length,
      num = 0;
    if (len === 0) return;
    if (officialLetter) {
      if (!status) {
        return len * parseFloat(order[0].multiple || 1);
      } else {
        if (len > 0) {
          order.forEach((v, i) => {
            num += parseFloat(v.multiple);
          });
        }
        return num;
      }
    } else {
      if (len > 0) {
        order.forEach((v, i) => {
          num += (parseFloat(v.multiple) * parseFloat(v.num) * 2);
        });
      }
      return num;
    }
  },
  //官方注数计算
  officialNote(order) {
    let num = 0;
    order.forEach((v, i) => {
      num += v.num;
    });
    return num;
  },
  loadingClose() {
    Indicator.close();
  },
  updata(that, funName, valueObj) {
    that.$store.commit(funName, valueObj);
  },
  /*官方投注方法*/
  /*一个玩法 | */
  takeLaws(arr, totalNotes) {
    let len = arr.length;
    let str = {};
    for (let i = 0; i < len; i++) {
      arr[i].forEach((v) => {
        totalNotes += v + '|';
      })
    }
    str.number = totalNotes.substring(0, totalNotes.length - 1);
    return str;
  },
  /*两个以及以上的玩法*/
  takeLawsTwo(arr, totalNotes) {
    let len = arr.length;
    let str = {};
    for (var i = 0; i < len; i++) {
      if (arr[i].length === 0) {
        totalNotes += '|';
        continue
      }
      ;
      totalNotes += '' + arr[i].sort() + '|';
    }
    str.number = totalNotes.substring(0, totalNotes.length - 1);
    return str;
  },
  conditionSet(len, val) {
    let that = this;
    if (len > val) {
      that.showAlert('本玩法最多支持选择' + val + '个号码');
      return false;
    } else {
      return true;
    }
  },
  topTwo(arr) {

  },
  topThree(arr) {
    let totalNum = 0;
    for (let i = 0; i < arr[0].length; i++) {
      for (let j = 0; j < arr[1].length; j++) {
        if (arr[0][i] == arr[1][j]) {
          continue;
        }
        let repetCount = 0;
        if (arr[2].indexOf(arr[0][i]) > -1) {
          repetCount++;
        }
        if (arr[2].indexOf(arr[1][j]) > -1) {
          repetCount++;
        }
        let count = arr[2].length - repetCount;
        totalNum += count;
      }
    }
    return totalNum;
  },
  calculationsNum(arr) {
    let num = 0;
    arr.forEach((v) => {
      num += v.length;
    });
    return num;
  },
  calculationsRide(arr, id) {
    let num = 0,
      u = 1,
      len = arr.length;
    for (let i = 0; i < len; i++) {
      if (arr[i].length === 0 && i < id) {
        u = 0;
      } else {
        if (arr[i].length === 0) continue;
      }
      u = u * arr[i].length;
    }
    num = u;
    return num;
  },
  //单式
  orderNumber(arr, id) {
    let str = {},
      totalNotes = '',
      num = 0;
    arr.forEach((v, i) => {
      i += 1;
      if (v.length === 0) {
        false;
      } else {
        if (i % id === 0) {
          totalNotes += v + '|';
          num += 1;
        } else {
          totalNotes += v + ',';
        }
      }
    });
    str.number = totalNotes.substring(0, totalNotes.length - 1);
    str.num = num;
    return str;
  },
  //信用返点计算
  creditRebateCal(ball, returnVal, officialVal, personalVal) {
    let ballOdds = parseInt(Math.round(ball.odds * 1000)),   //最大赔率
      smallOdds = parseInt(Math.round(ball.oddsMin * 1000));  //最小赔率
    returnVal = parseInt(Math.round(returnVal * 10)) / 2; //返点
    officialVal = parseInt(Math.round(officialVal * 10)); //官方返点
    personalVal = parseInt(Math.round(personalVal * 10)); //个人返点
    if (ballOdds === 0 && smallOdds === 0) {
      return 0;
    } else {
      // var val = (((((ballOdds - smallOdds) / officialVal * personalVal + smallOdds - (ballOdds - smallOdds) * returnVal / officialVal) / ballOdds) * ballOdds) / 10000);
      let one = (personalVal - returnVal) / officialVal;
      let val = ((ballOdds - smallOdds) * one + smallOdds) / 1000;
      return Math.floor(val * 1000) / 1000;
    }
  },
  //总注数计算
  totalNumberNotes(order) {
    let len = order.length,
      amount = 0,
      str = {};
    order.forEach((v, i) => {
      amount += parseFloat(v.amount);
    });
    str.num = len;
    str.amount = amount;
    return str;
  },
  //设置cookies
  setCookie(name, value, days) {
    var d = new Date();
    days = !days || 0;
    d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    // console.info(cname + "=" + cvalue + "; " + expires);
    document.cookie = name + "=" + value + "; " + days;
  },
  //日期转换
  formatDateTime(timeStamp, isTime, type) {
    var date = new Date();
    date.setTime(timeStamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    type = type || '-';
    if (isTime) {
      return y + type + m + type + d + ' ' + h + ':' + minute + ':' + second;
    } else {
      return y + type + m + type + d;
    }

  },
  formatDateTime2(timeStr, isTime, type) {
    var date = new Date(timeStr);
    // date.setTime(timeStr);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    type = type || '-';
    if (isTime) {
      return y + type + m + type + d + ' ' + h + ':' + minute + ':' + second;
    } else {
      return y + type + m + type + d;
    }

  },
  //当前日期
  currentDateYear(id) {
    var dd = new Date();
    dd.setDate(dd.getDate() + id);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;//获取当前月份的日期
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
  },
  //保留只能输入小数点和数字
  clearNoNum(obj) {
    let value = '';
    value = obj.value.replace(/[^\d.]/g, "");
    value = obj.value.replace(/\.{2,}/g, ".");
    value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    if (value.indexOf(".") < 0 && value != "") {
      value = parseFloat(value);
    }
    return value;
  },
  lotteryWidthPx(val) {
    let height = $(window).height();
    let j = height - val;
    return j
  },
  //获取彩种的的name
  lotteryNameUtils(code) {
    let str = {
      name: '',
      index: ''
    };
    switch (code) {
      case '001':
      case '003':
      case '005':
      case '007':
      case '009':
      case '011':
      case '012':
      case '013':
      case '014':
      case '015':
      case '017':
      case '019':
      case '021':
      case '024':
      case '025':
      case '1001':
      case '1002':
      case '1003':
        str.name = 'credit';
        break;
      case '002':
      case '004':
      case '006':
      case '008':
      case '010':
      case '016':
      case '018':
      case '020':
      case '022':
      case '023':
      case '026':
        str.name = 'official';
        break;
      case '2001':
        str.name = 'baccarat';
        break;
      case '2002':
        str.name = 'adventures';
        break;
    }

    return str;
  },
  checkLotteryCode(code) {
    let lotteryCode = {
      '003': '004',
      '004': '003',
      '001': '002',
      '002': '001',
      '005': '006',
      '006': '005',
      '010': '011',
      '011': '010',
      '023': '024',
      '024': '023',
      '016': '015',
      '015': '016',
      '017': '018',
      '018': '017',
      '019': '020',
      '020': '019',
      '021': '022',
      '022': '021',
    }
    if (lotteryCode[code]) {
      return lotteryCode[code];
    } else {
      return '-1';
    }
  },
  // 金币动画
  parabola(that, e, location, index, scrollDistance,isAllIn) {
    // let that = this;
    let flyFunc = function () {
      let chip = location.find(".chip");
      let offsetImg = chip.find("img").offset();
      let chipImg = $(".chipItem.chipOn").find("img");
      let chipImgOffset = chipImg.offset();
      let flyer = chipImg.clone();
      flyer.attr({
        "class": "cloneImg"
      }).offset({
        top: chipImgOffset.top,
        left: chipImgOffset.left
      }).css({
        "position": "absolute",
        "width": "1.8rem",
        "height": "1.8rem",
        "margin-left": "0.5rem",
        "z-index": "1000"
      });
      flyer.fly({
        speed: 1.8,
        start: {
          left: chipImgOffset.left,
          top: chipImgOffset.top
        },
        end: {
          left: offsetImg.left || 0,
          top: offsetImg.top - (scrollDistance || 0),
          width: 35,
          height: 35
        },
        onEnd: function () {
          chip.find('img').attr('src', flyer.attr('src'));
          if(isAllIn){
            chip.addClass("allIn");
          }
          let flyThat = this;
          setTimeout(function () {
            flyThat.destroy();
          }, 40);
        }
      });
    };
    flyFunc();
  },
  //球号相加结果
  sumNum(arr) {
    let result = 0;
    arr.forEach((v,i) => {
      if (v == "?") {
        result = '?';
      } else {
        if(i >= 3) return;
        result += parseFloat(v);
      }
    });
    return result;
  },
  whetherLogin() {
    let loginTrue = this.getItem('loginStatus');
    return loginTrue;
  },
  getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    // console.log('document.cookie', document.cookie)
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1);
      if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
  }
}
